<script setup>
import { ref, reactive, onMounted, toRaw, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {Edit, Delete, Search} from '@element-plus/icons-vue'

//引入API
import { findAllEmps } from '../../api/emp.js'

// sex: 1男, 2女; marry: 1未婚,2已婚; status: 1试用, 2正式, 3离职, 4实习;
const tableLoading = ref(true);//表格数据加载标识
// 数据
const currentPageNum = ref(1);//当前页码
const currentPageSize = ref(5);//每页显示的最大数据量
const dataArr = ref([]);//当前页数据
const total = ref(0);//总数据量

function doLoadTableDatas() {//加载表格数据
    tableLoading.value = true;//开始加载
    //TODO: 使用API(提供了数据服务才能使用,否则会出错)根据条件加载数据
    /* //示例
    findAllEmps().then((response)=>{
        console.log('findAllEmps-ok:', response);
    }).catch((err)=>{
        //请求的错误将被拦截器处理,上述then中处理出错时,才会进入此catch,故此时可省略catch
        console.log('findAllEmps-err:', err);
    });
    */

    //主要查询条件
    let params = {
        pageNum: currentPageNum.value,
        pageSize: currentPageSize.value,
        edu: searchFormData.value.edu,
        hiredate: toRaw(searchFormData.value.hiredate),//注意格式,此处是数组
        marry: searchFormData.value.marry,
        name: searchFormData.value.name,
        no: searchFormData.value.no,
        phone: searchFormData.value.phone,
        sex: searchFormData.value.sex,
        status: searchFormData.value.status,
    };
    console.log('search params:', params);

    //模拟数据加载操作
    const loadData = () => {
        return {
            total: 100,
            data: [
                {id:1,loginName:'tom1',no:'000001',name:'汤姆1汤姆1',idCard:'999999999999999999',sex:1,phone:'12345678901',addr:'南京1',marry:1,school:'XXX大学1',edu:'本科',hiredate:'2000-10-20',expirationTime:'2099-10-20',dept:{id:1,name:'开发部'},job:{id:1,name:'Java工程师'},status:2},
                {id:2,loginName:'tom2',no:'000002',name:'汤姆2',idCard:'123456789012345672',sex:2,phone:'12345678902',addr:'南京2',marry:2,school:'XXX大学2',edu:'本科',hiredate:'2024-08-20',expirationTime:'2024-11-20',dept:{id:1,name:'开发部'},job:{id:1,name:'前端工程师'},status:1},
                {id:3,loginName:'tom3',no:'000003',name:'汤姆3',idCard:'123456789012345673',sex:2,phone:'12345678903',addr:'南京3',marry:1,school:'XXX大学3',edu:'本科',hiredate:'2000-10-20',expirationTime:'2099-10-20',dept:{id:1,name:'开发部'},job:{id:1,name:'Java工程师'},status:2},
                {id:4,loginName:'tom4',no:'000004',name:'汤姆4',idCard:'123456789012345674',sex:1,phone:'12345678904',addr:'南京4',marry:1,school:'XXX大学4',edu:'本科',hiredate:'2000-10-20',expirationTime:'2099-10-20',dept:{id:1,name:'开发部'},job:{id:1,name:'Java工程师'},status:2},
                {id:5,loginName:'tom5',no:'000005',name:'汤姆5',idCard:'123456789012345675',sex:1,phone:'12345678905',addr:'南京5',marry:1,school:'XXX大学5',edu:'本科',hiredate:'2000-10-20',expirationTime:'2099-10-20',dept:{id:1,name:'开发部'},job:{id:1,name:'Java工程师'},status:2}
            ]
        }
    };
    const result = loadData();

    //成功后执行以下操作
    //处理响应数据
    dataArr.value = result.data;
    total.value = result.total;
    setTimeout(()=>{//模拟响应结束
        tableLoading.value = false;//加载完成
    },500);

}

onMounted(()=> {//挂载后执行
    doLoadDeptDatas();//部门数据
    doLoadJobDatas();//职位数据
    doLoadTableDatas();//核心表格数据
});

//格式化数据
function getSex(row) {
    return row.sex == 1 ? '男':'女';
}
function getMarry(row) {
    return row.marry == 1 ? '未婚':'已婚';
}
const statusStrArr = [undefined,'试用','正式','离职','实习'];
function getStatus(row) {
    return statusStrArr[row.status]||'未知';
}

const tableSelectObj = ref(null);//选中行对象
function doTableSelectionChange(selected) {//选中操作
    //选中变化
    console.log('doTableSelectionChange:', selected);
    tableSelectObj.value = selected;
}

//一次只能操作一个数据
function doModify() {//修改对话框
    if(tableSelectObj.value == null) {
        ElMessage.warning('请选择需要修改的行');
        return;
    }
    //设置数据
    const obj = toRaw(tableSelectObj.value);//取原对象
    const newValue = structuredClone(obj);//克隆
    formData.value = newValue;

    //成功后打开对话框
    dialogFlag.value = true;
}
function doRemove() {//删除
    if(tableSelectObj.value == null) {
        ElMessage.warning('请选择需要删除的行');
        return;
    }
    //TODO: 执行数据删除

    //成功后执行以下操作
    ElMessage.success('删除成功');
    //重新加载数据
    doLoadTableDatas();
}
function doModifyStatus() {//未使用
    if(tableSelectObj.value == null) {
        ElMessage.warning('请选择需要修改的行');
        return;
    }
}

function createFormData() {//表单数据对象模板
    return {id:undefined,loginName:'',pwd:'',no:'',name:'',idCard:'',sex:1,phone:'',addr:'',marry:1,school:'',edu:'',hiredate:'',expirationTime:'',dept:{id:undefined,name:''},job:{id:undefined,name:''},status:1};
}
//对话框中表单数据
const formData = ref(createFormData());
const dialogFlag = ref(false);
function doDialogBeforeClose(done) {
    //关闭操作
    done();
    formRef.value.clearValidate();//清除校验标记
}
function doCloseDialog(type) {
    if(type === 0) {
        //取消操作
        dialogFlag.value = false;
        formRef.value.clearValidate();//清除校验标记
        return;
    }
    if(type === 1) {
        //确定操作
        doFormSubmit();
    }
}

const formRef = ref(null);//表单组件
const formRules = reactive({//校验规则
    //no: [{required:true, message:'请填写工号', trigger:'blur'}],
    name: [
        {required:true, message:'请填写姓名', trigger:'blur'},
        {min:1, max:20, message:'长度是1~20', trigger:'blur'},
    ],
    idCard: [
        {required:true, message:'请填写身份证号', trigger:'blur'},
        {min:1, max:18, message:'长度是1~18', trigger:'blur'},
    ],
    sex: [{required:true, validator: (rule, value, callback)=>{
        if(value != 1 && value != 2) {
            callback(new Error('请选择性别'));
            return;
        }
        callback();
    }, trigger:'change'}],
    phone: [{required:true, message:'请填写手机号', trigger:'blur'}],
    addr: [{required:false, max:150, message:'长度要小于150', trigger:'blur'}],
    marry: [{required:true, validator: (rule, value, callback)=>{
        if(value != 1 && value != 2) {
            callback(new Error('请选择婚姻状况'));
            return;
        }
        callback();
    }, trigger:'change'}],
    school: [{required:false, max:50, message:'长度要小于50', trigger:'blur'}],
    edu: [{required:false, max:10, message:'长度要小于10', trigger:'blur'}],
    hiredate: [{type:'string', required:true, message:'请填写生日', trigger:'change'}],
    expirationTime: [{type:'string', required:true, message:'请填写合同到期时间', trigger:'change'}],
    "dept.id": [{required:true, type:'number', message:'请选择部门', trigger:'change'}],
    "job.id": [{required:true, type:'number', message:'请选择职位', trigger:'change'}],
    status: [{required:true, message:'请选择状态', trigger:'change'}],
});
function doFormSubmit() {//表单校验与提交
    formRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('校验通过');
            //TODO: 提交修改的数据
            let params = toRaw(formData.value);
            params.deptId = formData.value.dept.id;
            params.jobId = formData.value.job.id;
            console.log('submit:', params);

            //成功后执行以下操作
            dialogFlag.value = false;//成功,关闭对话框
            ElMessage.success('修改成功');
            //重新加载数据
            doLoadTableDatas();
        } else { 
            //console.log('校验不通过:', fields);
            ElMessage.warning('信息有误，请查看对应的提示信息');
        }
    });;
}
function doFormReset() {//表单重置, 未使用
    formRef.value.resetFields();
}

const deptArr = ref([]);
function doLoadDeptDatas() {//加载部门选择框数据
    //TODO: 使用API获取数据
    let data = [
        {id:1, name:'开发部'},
        {id:2, name:'运维部'},
        {id:3, name:'销售部'},
        {id:4, name:'行政部'},
        {id:5, name:'设备部'}
    ];
    
    //成功后执行以下操作
    deptArr.value = data;
}
const jobArr = ref([]);
function doLoadJobDatas() {//加载职位选择框数据
    //TODO: 使用API获取数据
    let data = [
        {id:1, name:'Java工程师'},
        {id:2, name:'前端工程师'},
        {id:3, name:'UI工程师'},
        {id:4, name:'人力资源'},
        {id:5, name:'部门经理'}
    ];

    //成功后执行以下操作
    jobArr.value = data;
}

//搜索
const searchFormData = ref({no:'',name:'',phone:'',sex:0,marry:0,hiredate:[],edu:'',status:0});
const searchFormRef = ref(null);
function doFormSearch() {
    if(tableLoading.value) {
        ElMessage.warning('正在查询中...');
        return;
    }
    //console.log('searchFormData:', toRaw(searchFormData.value));
    let oldPageNum = currentPageNum.value;
    currentPageNum.value = 1;//从头开始查询,改变currentPage会触发下方的watch
    if(oldPageNum == 1) {//防止重复加载
        // 根据条件加载数据
        doLoadTableDatas();
    }
}

//分页变化,加载数据
watch(currentPageNum, (nv, ov, onCleanup)=>{
    doLoadTableDatas();
});
watch(currentPageSize, (nv, ov, onCleanup)=>{
    doLoadTableDatas();
});

</script>
<template>
    <div>
        <div class="title-dl">员工信息列表</div>
        <div class="tool-btns" >
            <!-- search表单 -->
            <el-form :model="searchFormData" :inline="true" ref="searchFormRef">
                <el-form-item label="工号：" prop="no">
                    <el-input v-model="searchFormData.no" autocomplete="off" placeholder="请输入" clearable style="width: 160px" />
                </el-form-item>
                <el-form-item label="姓名：" prop="name">
                    <el-input v-model="searchFormData.name" autocomplete="off" placeholder="请输入" clearable style="width: 160px" />
                </el-form-item>
                <el-form-item label="手机号：" prop="phone">
                    <el-input v-model="searchFormData.phone" autocomplete="off" placeholder="请输入" clearable style="width: 160px" />
                </el-form-item>
                <el-form-item label="性别：" prop="sex">
                    <el-select v-model="searchFormData.sex" placeholder="请选择" style="width:100px" >
                        <el-option label="全部" :value="0"/>
                        <el-option label="男" :value="1"/>
                        <el-option label="女" :value="2"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="婚姻状况：" prop="marry">
                    <el-select v-model="searchFormData.marry" placeholder="请选择" style="width:100px">
                        <el-option label="全部" :value="0"/>
                        <el-option label="未婚" :value="1"/>
                        <el-option label="已婚" :value="2"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="入职日期：" prop="hiredate">
                    <el-date-picker type="daterange" v-model="searchFormData.hiredate" 
                    value-format="YYYY-MM-DD"
                    start-placeholder="开始日期"
                    range-separator="至"
                    end-placeholder="结束日期"
                    />
                </el-form-item>
                <el-form-item label="学历：" prop="edu">
                    <el-select v-model="searchFormData.edu" placeholder="请选择" style="width:100px">
                        <el-option label="全部" value=""/>
                        <el-option label="大专以下" value="大专以下"/>
                        <el-option label="大专" value="大专"/>
                        <el-option label="本科" value="本科"/>
                        <el-option label="硕士" value="硕士"/>
                        <el-option label="博士" value="博士"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态：" prop="status">
                    <el-select v-model="searchFormData.status" placeholder="请选择" style="width:100px" >
                        <el-option label="全部" :value="0"/>
                        <el-option label="试用" :value="1"/>
                        <el-option label="正式" :value="2"/>
                        <el-option label="离职" :value="3"/>
                        <el-option label="实习" :value="4"/>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="doFormSearch">查询</el-button>
                </el-form-item>
            </el-form>

            <el-button type="primary" :icon="Edit" @click="doModify">修改</el-button>
            <el-button type="danger" :icon="Delete" @click="doRemove">删除</el-button>
            <!-- <el-button type="success" :icon="Edit" @click="doModifyStatus">状态修改</el-button> -->
        </div>
        <div class="content-dl" v-loading="tableLoading" >
            <!-- 根据情况增减列 -->
            <el-table :data="dataArr" stripe border @current-change="doTableSelectionChange" highlight-current-row>
                <el-table-column prop="no" label="工号" width="80" fixed />
                <el-table-column prop="name" label="姓名" width="100" fixed />
                <el-table-column prop="loginName" label="登录名" show-overflow-tooltip />
                <el-table-column prop="idCard" label="身份证" width="180" />
                <el-table-column prop="sex" label="性别" width="60" :formatter="getSex" />
                <el-table-column prop="phone" label="手机" width="120" />
                <el-table-column prop="addr" label="居住地" show-overflow-tooltip />
                <el-table-column prop="marry" label="婚姻" width="60" :formatter="getMarry" />
                <el-table-column prop="school" label="学校" show-overflow-tooltip />
                <el-table-column prop="edu" label="学历" width="60" show-overflow-tooltip />
                <el-table-column prop="hiredate" label="入职" width="120" />
                <el-table-column prop="expirationTime" label="合同到期" width="120" />
                <el-table-column prop="dept.name" label="部门" width="120" show-overflow-tooltip />
                <el-table-column prop="job.name" label="职位" width="150" show-overflow-tooltip />
                <el-table-column prop="status" label="状态" width="80" :formatter="getStatus" />
            </el-table>
            <el-pagination class="page-dl" layout="total, jumper, prev, pager, next" :total="total" 
            v-model:current-page="currentPageNum" v-model:page-size="currentPageSize"
            :pager-count="5" hide-on-single-page size="large" />
        </div>

        <!-- 修改对话框 destroy-on-close关闭时销毁 -->
        <el-dialog v-model="dialogFlag" title="员工编辑" width="600" 
        :before-close="doDialogBeforeClose" center align-center draggable 
        @opened="console.log('opened:', Date.now())"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        >
            <el-form :model="formData" label-width="130px" :rules="formRules" 
            status-icon ref="formRef">
                <el-form-item label="工号：" prop="no">
                    <el-input v-model="formData.no" autocomplete="off" readonly />
                </el-form-item>
                <el-form-item label="姓名：" prop="name">
                    <el-input v-model="formData.name" autocomplete="off" />
                </el-form-item>
                <!-- <el-form-item label="用户名：" prop="loginName">
                    <el-input v-model="formData.loginName" autocomplete="off" />
                </el-form-item> -->
                <!-- <el-form-item label="新密码：" prop="pwd">
                    <el-input type="password" v-model="formData.pwd" autocomplete="off" placeholder="填写则修改密码" show-password />
                </el-form-item> -->
                <el-form-item label="身份证号：" prop="idCard">
                    <el-input v-model="formData.idCard" autocomplete="off" />
                </el-form-item>
                <el-form-item label="性别：" prop="sex">
                    <el-radio-group v-model="formData.sex">
                        <el-radio label="男" :value="1"/><el-radio label="女" :value="2"/>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="手机号：" prop="phone">
                    <el-input v-model="formData.phone" autocomplete="off" />
                </el-form-item>
                <el-form-item label="居住地：" prop="addr">
                    <el-input type="textarea" v-model="formData.addr" autocomplete="off" autosize />
                </el-form-item>
                <el-form-item label="婚姻状况：" prop="marry">
                    <el-radio-group v-model="formData.marry">
                        <el-radio label="未婚" :value="1"/><el-radio label="已婚" :value="2"/>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="毕业学校：" prop="school">
                    <el-input v-model="formData.school" autocomplete="off" />
                </el-form-item>
                <el-form-item label="学历：" prop="edu">
                    <el-select v-model="formData.edu" placeholder="请选择" >
                        <el-option label="大专以下" value="大专以下"/>
                        <el-option label="大专" value="大专"/>
                        <el-option label="本科" value="本科"/>
                        <el-option label="硕士" value="硕士"/>
                        <el-option label="博士" value="博士"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="入职日期：" prop="hiredate">
                    <el-date-picker v-model="formData.hiredate" value-format="YYYY-MM-DD" 
                    placeholder="请选择" />
                </el-form-item>
                <el-form-item label="合同到期时间：" prop="expirationTime">
                    <el-date-picker v-model="formData.expirationTime" value-format="YYYY-MM-DD" 
                    placeholder="请选择" />
                </el-form-item>
                <el-form-item label="部门：" prop="dept.id">
                    <el-select v-model="formData.dept.id" placeholder="请选择" >
                        <el-option v-for="d in deptArr" :key="d.id" :label="d.name" :value="d.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="职位：" prop="job.id">
                    <el-select v-model="formData.job.id" placeholder="请选择" >
                        <el-option v-for="j in jobArr" :key="j.id" :label="j.name" :value="j.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态：" prop="status">
                    <el-select v-model="formData.status" placeholder="请选择" >
                        <el-option label="试用" :value="1"/>
                        <el-option label="正式" :value="2"/>
                        <el-option label="离职" :value="3"/>
                        <el-option label="实习" :value="4"/>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="doCloseDialog(0)">取消</el-button>
                    <el-button type="primary" @click="doCloseDialog(1)">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<style scoped>
.title-dl {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 10px;
}
.tool-btns {
    margin-bottom: 10px;
}
.page-dl {
    margin-top: 10px;
}
</style>